<?php

include_once('image_resizer.php');

/**
 * Created by PhpStorm.
 * User: freewheel
 * Date: 2016/10/13
 * Time: 9:51
 */
abstract class DB_Operation
{
    abstract public function operate($conn);

    abstract public function getImageDir();

    public function getImageExtension($target_dir)
    {
        if (!isset($_FILES["image"]))
            return "NotImageFound";

        $target_file = $target_dir . basename($_FILES["image"]["name"]);
        $imageFileType = pathinfo($target_file, PATHINFO_EXTENSION);
        return $imageFileType;
    }

    public function validate_image($imageFileType)
    {
        if (!isset($_FILES["image"])) {
            return "No image found!";
        }

        $check = getimagesize($_FILES["image"]["tmp_name"]);
        if ($check === false) {
            return "No valid image found!";
        }

        if ($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif") {
            return "Invalid image extension! Only JPG, JPEG, PNG & GIF files are allowed.";
        }

        if ($_FILES["image"]["size"] > 10000000) {
            return " Image is too large, should be less than 10M ";
        }

        return "OK";
    }

    public function upload_image($target_dir, $resized_dir, $custom_filename)
    {
        $target_file = $target_dir . $custom_filename;
        $resized_file = $resized_dir . $custom_filename;

        if (file_exists($target_file)) {
            unlink($target_file);
        }

        if (file_exists($resized_file)) {
            unlink($resized_file);
        }

        if (move_uploaded_file($_FILES["image"]["tmp_name"], $target_file)) {
//            echo "The file " . basename($_FILES["image"]["name"]) . " has been uploaded.";
            smart_resize_image($target_file,null , 200, 200, true, 'newimage', false, false, 100, $resized_file);
        } else {
            throw new Exception("Sorry, there was an error when uploading  file.");
        }

    }

    public function delete_image($target_dir, $custom_filename)
    {
        $target_file = $target_dir . $custom_filename;

        if (file_exists($target_file)) {
            unlink($target_file);
        }
    }
}